const BaseService = require('./base_service.js');
const RechargeLevelModel = require('../model/recharge_level_model.js');
const UserRechargeLogModel = require('../model/user_recharge_log_model.js');
const UserModel = require('../model/user_model.js');

class RechargeManagementService extends BaseService {

  /**
   * 配置充值档位
   */
  async configRechargeLevels(levels) {
    const db = uniCloud.database();
    const collection = db.collection(RechargeLevelModel.CL);

    // 清空现有档位
    await collection.where({}).remove();

    // 添加新档位
    const levelData = levels.map((level, index) => ({
      level: index + 1,
      amount: level.amount,
      bonus: level.bonus || 0,
      totalAmount: level.amount + (level.bonus || 0),
      description: level.description,
      status: 1,
      sortOrder: index,
      createTime: Date.now(),
      updateTime: Date.now()
    }));

    const result = await collection.add(levelData);
    
    return {
      message: '充值档位配置成功',
      levels: levelData
    };
  }

  /**
   * 获取充值档位列表
   */
  async getRechargeLevels() {
    const db = uniCloud.database();
    const collection = db.collection(RechargeLevelModel.CL);

    const result = await collection
      .where({ status: 1 })
      .orderBy('sortOrder', 'asc')
      .get();

    return result.data;
  }

  /**
   * 管理员帮用户充值
   */
  async rechargeUser(input) {
    const db = uniCloud.database();
    const userCollection = db.collection(UserModel.CL);
    const logCollection = db.collection(UserRechargeLogModel.CL);

    // 检查用户是否存在
    const user = await userCollection.doc(input.userId).get();
    if (!user.data.length) {
      throw new Error('用户不存在');
    }

    const userData = user.data[0];
    const totalAmount = input.amount + (input.bonus || 0);

    // 更新用户余额
    await userCollection.doc(input.userId).update({
      balance: db.command.inc(totalAmount),
      updateTime: Date.now()
    });

    // 记录充值日志
    const logData = {
      userId: input.userId,
      userPhone: userData.phone,
      amount: input.amount,
      bonus: input.bonus || 0,
      totalAmount: totalAmount,
      rechargeType: 'admin',
      operatorId: this.getCurrentAdminId(),
      operatorName: this.getCurrentAdminName(),
      reason: input.reason,
      paymentMethod: 'balance',
      status: 1,
      createTime: Date.now(),
      updateTime: Date.now()
    };

    await logCollection.add(logData);

    return {
      message: '用户充值成功',
      amount: input.amount,
      bonus: input.bonus || 0,
      totalAmount: totalAmount,
      newBalance: userData.balance + totalAmount
    };
  }

  /**
   * 扣除用户余额
   */
  async deductUserBalance(input) {
    const db = uniCloud.database();
    const userCollection = db.collection(UserModel.CL);
    const logCollection = db.collection(UserRechargeLogModel.CL);

    // 检查用户是否存在
    const user = await userCollection.doc(input.userId).get();
    if (!user.data.length) {
      throw new Error('用户不存在');
    }

    const userData = user.data[0];

    // 检查余额是否足够
    if (userData.balance < input.amount) {
      throw new Error('用户余额不足');
    }

    // 更新用户余额
    await userCollection.doc(input.userId).update({
      balance: db.command.inc(-input.amount),
      updateTime: Date.now()
    });

    // 记录扣除日志
    const logData = {
      userId: input.userId,
      userPhone: userData.phone,
      amount: -input.amount,
      bonus: 0,
      totalAmount: -input.amount,
      rechargeType: 'admin',
      operatorId: this.getCurrentAdminId(),
      operatorName: this.getCurrentAdminName(),
      reason: input.reason,
      paymentMethod: 'balance',
      status: 1,
      createTime: Date.now(),
      updateTime: Date.now()
    };

    await logCollection.add(logData);

    return {
      message: '用户余额扣除成功',
      amount: input.amount,
      newBalance: userData.balance - input.amount
    };
  }

  /**
   * 获取用户充值记录
   */
  async getUserRechargeLogs(input) {
    const db = uniCloud.database();
    const collection = db.collection(UserRechargeLogModel.CL);

    // 构建查询条件
    let whereCondition = {};
    
    if (input.userId) {
      whereCondition.userId = input.userId;
    }
    
    if (input.dateRange) {
      const dates = input.dateRange.split(',');
      if (dates.length === 2) {
        whereCondition.createTime = db.command.gte(parseInt(dates[0])).and(db.command.lte(parseInt(dates[1])));
      }
    }

    // 分页查询
    const result = await collection
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((input.page - 1) * input.size)
      .limit(input.size)
      .get();

    // 获取总数
    const countResult = await collection.where(whereCondition).count();

    return {
      list: result.data,
      total: countResult.total,
      page: input.page,
      size: input.size
    };
  }

  /**
   * 获取当前管理员ID
   */
  getCurrentAdminId() {
    // 这里应该从请求上下文中获取当前管理员ID
    // 由于具体实现需要根据认证机制，这里先返回模拟值
    return 'admin_001';
  }

  /**
   * 获取当前管理员姓名
   */
  getCurrentAdminName() {
    // 这里应该从请求上下文中获取当前管理员姓名
    return '管理员';
  }
}

module.exports = RechargeManagementService;
